//
//  WXSPlayerManager.m
//  SmartRecorderTest
//
//  Created by 王勇 on 16/9/20.
//  Copyright © 2016年 王勇. All rights reserved.
//

#import "WXSPlayerManager.h"

@interface WXSPlayerManager()

@property (nonatomic,copy)NSMutableDictionary *audioPlayers;

@end

static WXSPlayerManager *manager = nil;
@implementation WXSPlayerManager

+(instancetype)sharedManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc]init];
    });
    return manager;
}

-(instancetype)init{
    __block WXSPlayerManager *temp = self;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        temp = [super init];
        if (temp) {
            AVAudioSession *session = [AVAudioSession sharedInstance];
            [session setCategory:AVAudioSessionCategoryPlayback error:nil];
            [session setActive:YES error:nil];
        }
    });
    
    self = temp;
    return self;
}

-(AVAudioPlayer*)playAudioFile:(NSString *)fileName{
    if (fileName == nil || fileName.length == 0) {
        return nil;
    }
    
    AVAudioPlayer *player = self.audioPlayers[fileName];
    if (player == nil) {
        
        NSURL *url = [NSURL fileURLWithPath:fileName];
        if (url == nil) {
            return nil;
        }
        
        NSError *error = nil;
        player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
        if (error) {
            NSLog(@"播放器初始化错误!");
            return nil;
        }
        
        if (![player prepareToPlay]) {
            return nil;
        }
        
        self.audioPlayers[fileName] = player;
    }
    
    if (![player isPlaying]) {
        [player play];
    }
    
    return player;
}


/**
 *  Pause the audio file being played.
 *
 *  @param fileName the full path of the audio file which needs to be paused
 */
-(void)pauseAudioFile:(NSString *)fileName{
    if (fileName == nil || fileName.length == 0) {
        return;
    }
    
    AVAudioPlayer *player = self.audioPlayers[fileName];
    if ([player isPlaying]) {
        [player pause];
    }
}

-(void)stopPlayingAudio:(NSString *)fileName{
    if (fileName == nil || fileName.length == 0) {
        return;
    }
    
    AVAudioPlayer *player = self.audioPlayers[fileName];
    if ([player isPlaying]) {
        [player stop];
        player.currentTime = 0;
    }
}

-(NSMutableArray*)allAudioFilesInDirectory:(NSString*)fileDirectory{
    NSMutableArray *returnArrM = [NSMutableArray array];
    
    NSError *error = nil;
    NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fileDirectory error:&error];
    if (error) {
        NSLog(@"Error occured while loading record files! %@",error.localizedDescription);
        return nil;
    }
    
    if (array != nil) {
        [returnArrM addObjectsFromArray:array];
        
        __block NSInteger flag = 0;
        NSMutableArray *tempArrM = [returnArrM mutableCopy];
        [returnArrM enumerateObjectsUsingBlock:^(__strong NSString *  fileName, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (![fileName containsString:@".caf"]) {//不是录音文件
                [tempArrM removeObject:fileName];
                flag++;
            }else{
                fileName = [fileDirectory stringByAppendingPathComponent:fileName];
                [tempArrM replaceObjectAtIndex:idx-flag withObject:fileName];
            }
        }];
        
        returnArrM = [tempArrM mutableCopy];

        return [returnArrM mutableCopy];
    }else{
        return nil;
    }
}


-(void)removeAudioFile:(NSString *)filePath{
    NSError *error = nil;
    [[NSFileManager defaultManager]removeItemAtPath:filePath error:&error];
    if (error) {
        NSLog(@"删除文件失败！%@",error.localizedDescription);
    }
}

-(NSMutableDictionary *)audioPlayers{
    if (!_audioPlayers) {
        _audioPlayers = [NSMutableDictionary dictionary];
    }
    return _audioPlayers;
}

#pragma mark - Private

//-(void)getLengthOfEachFile{
//    
//}

@end
